from typing import Dict, Literal, cast
import UnityPy

from utils.创建文件夹 import createFolder

file_map = {
    "CARD_Indx": "CARD_Indx",
    "CARD_Name": "CARD_Name",
    "CARD_Desc": "CARD_Desc",
    "CARD_RubyName": "CARD_Name",
    "CARD_RubyIndx": "CARD_Indx",
    "Card_Part": "CARD_Part",
    "Card_Pidx": "CARD_Pidx",
}

path_id_map: Dict[Literal["en", "jp"], Dict[int, str]] = {"en": {}, "jp": {}}
lang_map = {"ja-jp": "jp", "en-us": "en"}
obj_name_list = [
    "card_indx",
    "card_name",
    "card_desc",
    "card_part",
    "card_pidx",
    "card_rubyname",
    "card_rubyindx",
]


def gen_path_id_map(env: any):
    for obj in env.objects:
        if obj.type.name == "ResourceManager":
            rm = obj.read()
            for container, ptr in rm.m_Container.items():
                try:
                    data = ptr.read()
                    path_id = data.path_id
                    if len(container.split("/")[-2:]) < 2:
                        continue
                    _lang, _obj_name = container.split("/")[-2:]
                    if _obj_name in obj_name_list:
                        if _lang not in list(lang_map.keys()) + ["v130"]:
                            continue
                        if _lang == "v130":
                            _lang = "ja-jp"  # 解决 ruby_name 和 ruby_indx 的问题
                        path_id_map[lang_map[_lang]][path_id] = (
                            _obj_name.split("_")[0].upper()
                            + "_"
                            + _obj_name.split("_")[1].capitalize()
                        )
                except Exception:
                    ...
            break


def gen_new_data_unity3d(src: str, dst: str):
    env = UnityPy.load(src)
    gen_path_id_map(env)
    print(path_id_map)

    def helper(lang: Literal["en", "jp"]):
        for obj in env.objects:
            if obj.type.name == "TextAsset" and obj.path_id in path_id_map[lang].keys():
                data = obj.read()
                name: str = data.name
                print(lang, name)
                with open(f"output/6_res/{lang}/{file_map[name]}.txt", "rb") as f:
                    data.script = f.read()
                data.save()

    helper("en")
    helper("jp")
    with open(dst, "wb") as f:
        f.write(env.file.save())


if __name__ == "__main__":
    createFolder("output/7_res")
    gen_new_data_unity3d("data/data.unity3d", "output/7_res/data.unity3d")
